package com.qf.air.controller;

import com.qf.air.util.R;
import com.qf.air.vo.ResultVO;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 何星宇
 * @version V1.0
 * @Date 2021/11/5 19:20
 */

@RestController
@CrossOrigin(allowCredentials = "true")
public class EChartsController {
    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @GetMapping(value = "/echarts")
    public ResultVO echarts() throws IOException {
        SearchRequest request = new SearchRequest();
        request.indices("air_index");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        TermsAggregationBuilder termsAggregationBuilder = new TermsAggregationBuilder("Terms");
        termsAggregationBuilder.field("districtName.keyword");
        termsAggregationBuilder.size(5);
        SearchSourceBuilder searchSourceBuilder = sourceBuilder.aggregation(termsAggregationBuilder);
        request.source(searchSourceBuilder);
        SearchResponse response = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        Terms terms = response.getAggregations().get("Terms");
        List<Map> result = new ArrayList<>();
        for (Terms.Bucket bucket : terms.getBuckets()) {
            Map map = new HashMap();
            map.put("name", bucket.getKey());
            map.put("value", bucket.getDocCount());
            result.add(map);
        }

        return R.ok(result);
    }
}
